class Solution {
public:
    int d[5] = {-1, 0, 1, 0, -1};
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size(), n = m ? board[0].size() : 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word[0]) {
                    if (dfs(board, word, i, j, 0))
                        return true;
                }
            }
        }
        return false;
    }
    bool dfs(vector<vector<char>>& board, string& word, int i, int j, int pos) {
        if (board[i][j] != word[pos])
            return false;
        if (pos == word.size() - 1)
            return true;
        
        char c = board[i][j];
        board[i][j] = '*';
        for (int k = 0; k < 4; k++) {
            int x = i + d[k], y = j + d[k + 1];
            if (x >= 0 && x < board.size() && y >= 0 && y < board[0].size()) {
                if (dfs(board, word, x, y, pos + 1))
                    return true;
            }
        }
        board[i][j] = c;
        return false;
    }
};
